package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tongyao.common.SuperController;
import com.example.tongyao.system.entity.SysConfig;
import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.system.message.SystemMessage;
import com.example.tongyao.utils.DataResult;
import com.example.tongyao.utils.DateUtils;
import com.example.tongyao.utils.StringUtils;
import com.example.tongyao.utils.token.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统配置表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-08-18
 */
@RestController
@Api(tags = "系统_配置前端控制器")
@RequestMapping("/system/sys-config")
public class SysConfigController extends SuperController {

    @GetMapping(value = "/test")
    public String test() throws Exception{
        throw new Exception("123");
    }

    /**
     * 分页查询所有配置
     * @return
     */
    @ApiOperation(
            value = "查询父级",
            notes = "分页查询父级配置",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "configName",value = "配置名称"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/configParent" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult configParent(
            @RequestParam(required = false) String configName,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "create_time") String sortBy,
            @RequestParam(defaultValue = "asc") String order) {

        LambdaQueryWrapper<SysConfig> sysConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysConfigLambdaQueryWrapper.eq(SysConfig::getParentId,"0");
        if(StringUtils.isNotBlank(configName)){
            sysConfigLambdaQueryWrapper.like(SysConfig::getConfigName,configName);
        }

        sysConfigLambdaQueryWrapper.eq(SysConfig::getDelFlag,"1");
        sysConfigLambdaQueryWrapper.last(" order by "+sortBy+" "+order);

        Page<SysConfig> page = new Page<>(pageNo,pageSize);
        IPage<SysConfig> iPage = iSysConfigService.page(page,sysConfigLambdaQueryWrapper);
        return DataResult.setSuccess(iPage);
    }


    @ApiOperation(
            value = "查询配置",
            notes = "根据左侧父级配置，点击事件分页查询配置信息",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "configId",value = "配置编号",required = true),
            @ApiImplicitParam(name = "configName",value = "配置名称"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/page/{configId}" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult page(@PathVariable(value="configId") String configId,
                               @RequestParam(required = false) String configName,
                               @RequestParam(defaultValue = "1") int pageNo,
                               @RequestParam(defaultValue = "10") int pageSize,
                               @RequestParam(defaultValue = "create_time") String sortBy,
                               @RequestParam(defaultValue = "asc") String order) {

        //后面可以根据标准统一设置 配置编号是否 可以传入

        LambdaQueryWrapper<SysConfig> sysConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysConfigLambdaQueryWrapper.eq(SysConfig::getParentId,configId);

        if(StringUtils.isNotBlank(configName)){
            sysConfigLambdaQueryWrapper.like(SysConfig::getConfigName,configName);
        }

        sysConfigLambdaQueryWrapper.eq(SysConfig::getDelFlag,"1"); //后面可以做成根据配置的值查询已删除的还是未删除的
        sysConfigLambdaQueryWrapper.last(" order by "+sortBy+" "+order);

        Page<SysConfig> page = new Page<>(pageNo,pageSize);
        IPage<SysConfig> iPage = iSysConfigService.page(page,sysConfigLambdaQueryWrapper);
        return DataResult.setSuccess(iPage);
    }

    //排序字段做一个统一限制！！！！！


    @ApiOperation(
            value = "增加配置",
            notes = "增加一个配置",
            httpMethod = "POST")
    @PostMapping(value = "/save" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult save(@Valid @RequestBody(required = true) SysConfig sysConfig) {

        codeExist(sysConfig.getConfigKey());
        SysUser user = (SysUser) UserUtils.getUserInfo();

        sysConfig.setConfigEnabled(true);
        sysConfig.setDelFlag(1);

        sysConfig.setCreateBy(user.getUserId());
        sysConfig.setCreateTime(DateUtils.getDateTime());

        reuslt = iSysConfigService.save(sysConfig);
        if(!reuslt){
            throw new RuntimeException(SystemMessage.config+SystemMessage.add+SystemMessage.fail+SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "编辑配置",
            notes = "编辑一个配置，需根据configId字段。",
            httpMethod = "PUT")
    @PutMapping(value = "/edit" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult edit(@Valid @RequestBody SysConfig sysConfig){

        SysUser user = (SysUser) UserUtils.getUserInfo();

        LambdaUpdateWrapper<SysConfig> sysConfigLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if(StringUtils.isNotBlank(sysConfig.getConfigName())){
            sysConfigLambdaUpdateWrapper.set(SysConfig::getConfigName,sysConfig.getConfigName());
        }
        if(StringUtils.isNotBlank(sysConfig.getConfigKey())){
            codeExist(sysConfig.getConfigKey());
            sysConfigLambdaUpdateWrapper.set(SysConfig::getConfigKey,sysConfig.getConfigKey());
        }
        if(StringUtils.isNotBlank(sysConfig.getConfigValue())){
            sysConfigLambdaUpdateWrapper.set(SysConfig::getConfigValue,sysConfig.getConfigValue());
        }
        if(StringUtils.isNotNull(sysConfig.getSystemConfig())){
            sysConfigLambdaUpdateWrapper.set(SysConfig::getSystemConfig,sysConfig.getSystemConfig());
        }
        if(StringUtils.isNotNull(sysConfig.getRemark())){
            sysConfigLambdaUpdateWrapper.set(SysConfig::getRemark,sysConfig.getRemark());
        }
        if(StringUtils.isNotNull(sysConfig.getSort())){
            sysConfigLambdaUpdateWrapper.set(SysConfig::getSort,sysConfig.getSort());
        }


        sysConfigLambdaUpdateWrapper.set(SysConfig::getModifyBy,user.getUserId());
        sysConfigLambdaUpdateWrapper.set(SysConfig::getModifyTime,DateUtils.getDateTime());

        sysConfigLambdaUpdateWrapper.eq(SysConfig::getConfigId,sysConfig.getConfigId());

        reuslt = iSysConfigService.update(sysConfigLambdaUpdateWrapper);
        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.config+
                            SystemMessage.update+
                            SystemMessage.fail+
                            SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "删除配置",
            notes = "删除一个或多个配置",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictId",value = "配置编号，多个以英文逗号拼接",required = true),
    })
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult delete(@RequestParam String configId){

        List configIds = Arrays.asList(configId.split(","));
        for (Object config: configIds) {

            //删除配置
            LambdaUpdateWrapper<SysConfig> sysConfigLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            sysConfigLambdaUpdateWrapper
                    .set(SysConfig::getDelFlag,"0")
                    .eq(SysConfig::getConfigId,config);
            reuslt = iSysConfigService.update(sysConfigLambdaUpdateWrapper);
            if(!reuslt){
                throw new RuntimeException(
                        SystemMessage.config+
                                SystemMessage.delete+
                                SystemMessage.fail+
                                SystemMessage.a
                );
            }

        }
        return DataResult.setSuccess(null);
    }


    @ApiOperation(
            value = "更改状态",
            notes = "更改配置的启用禁用状态",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "configId",value = "配置编号",required = true),
            @ApiImplicitParam(name = "state",value = "配置状态（true为启用，false为禁用）",required = true)
    })
    @PutMapping(value = "/changeState" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult changeState(
            @RequestParam String configId,
            @RequestParam boolean state
    ){

        LambdaUpdateWrapper<SysConfig> sysConfigLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        sysConfigLambdaUpdateWrapper
                .set(SysConfig::isConfigEnabled,state)
                .eq(SysConfig::getConfigId,configId);
        reuslt = iSysConfigService.update(sysConfigLambdaUpdateWrapper);

        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.config +
                            SystemMessage.state+
                            SystemMessage.update +
                            SystemMessage.fail +
                            SystemMessage.a
            );
        }

        return DataResult.setSuccess(null);
    }

    /**
     * 判断配置编码是否存在
     * @param code
     * @return
     */
    public void codeExist(String code){
        int count = commonService.getCount("sys_config","config_key = '"+code+"' and del_flag = 1");
        if(count > 0){
            throw new RuntimeException(code+" 配置编码已存在！");
        }
    }
}
